package com.hbjsl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetDataSource;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.company.SubCompanyComInfo;
import weaver.hrm.job.JobTitlesComInfo;
import weaver.hrm.resource.ResourceComInfo;

/**
 * 人员同步接口类，主要用于将其他系统的组织人员信息同步到系统中，门户与OA都会使用
 * @author feng
 *
 */
public class HrmOrgManager extends BaseBean
{
	
	
	/**
	 * 组织人员同步
	 * @param sysType 系统类型 hr portal
	 */
	public void syncHrmOrg() {
		SynSubCompany();//分部同步
		SynDept();//部门同步
		SynJobtitle();//岗位同步
		synHrmResource();//人员同步
		
		try {
			SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo();
	    	DepartmentComInfo departmentComInfo=new DepartmentComInfo();
	    	ResourceComInfo resourceComInfo = new ResourceComInfo();
	    	JobTitlesComInfo jobTitlesComInfo=new JobTitlesComInfo();
	      
	    	subCompanyComInfo.removeCompanyCache();
	    	departmentComInfo.removeCompanyCache();
	    	resourceComInfo.removeResourceCache();
	    	jobTitlesComInfo.removeJobTitlesCache();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	/**
	 * 人员同步
	 */
	public void synHrmResource()
	  {
	    RecordSet rs = new RecordSet();
	    char separator = Util.getSeparator();
	    String today = TimeUtil.getCurrentDateString();
	    
	    RecordSetDataSource dataSource = new RecordSetDataSource("EHR");
	    String sql="select * from empview";
	    dataSource.execute(sql);
	    while(dataSource.next()) {
			
	    	String outkey = dataSource.getString("employeeid");
			String workcode = dataSource.getString("code"); //人员编号
			String lastname = dataSource.getString("name"); //用户名称
			String sex = dataSource.getString("sex"); //性别
			if("1".equals(sex)){
				sex = "0";
			}else if("0".equals(sex)){
				sex = "1";
			}

			String mobile =dataSource.getString("mobilephone"); //手机号
			String certificatenum =dataSource.getString("idcard"); //身份证
			//String certificatenum = ""; //身份证
			String telephone =""; //办公电话
			String mobilecall="";
			String email = "2" + workcode;
			if(certificatenum.length() == 18){
				email = "2" + workcode + certificatenum.substring(certificatenum.length() - 4 );; //电子邮箱
			}
			String status = dataSource.getString("personnelcategory"); //状态 ⼈员的状态（0:停⽤/离职，1:正常/在职，2:锁定，3:强制锁定）
			String managercode = dataSource.getString("employeePId"); //上级编码
			String dsporder =""; //顺序
			
			String jobtitlekey = dataSource.getString("postid"); //岗位编码
			String departmentkey = dataSource.getString("orgid"); //部门编码
			
		    String loginstatus=status.equals("01")?"1":"5"; //01在岗  02离职  07退休  99其他
			String subcompanyid = "";//分部ID
		    String departmentid = ""; //部门ID
			String managerid=""; //上级ID
			String jobtitle = "";//岗位ID
		    
		    //查询上级
		    if (!"".equals(managercode)){
		    	rs.execute("select id from hrmresource where outkey='" + managercode + "'");
		        if (rs.next()) {
		        	managerid = rs.getString("id");
		        }
		    }
		    //查询所属部门
		    sql = "select id,subcompanyid1 from hrmdepartment where outkey ='" +departmentkey+"'";
		    rs.execute(sql);
		    if (rs.next()){
		    	departmentid = rs.getString("id");
		        subcompanyid = rs.getString("subcompanyid1");
		    }    
	        //岗位处理
	        sql = "select id from hrmjobtitles where outkey='" + jobtitlekey + "'";
	        rs.execute(sql);
	        if (rs.next()) {
	        	jobtitle = Util.null2String(rs.getString("id"));
	        }
	        
	        writeLog("[HrmOrgManager.synHrmResource] workcode:" + workcode+" lastname:"+lastname+" loginstatus:"+loginstatus);
	        /*
	        if(workcode.equals("")){
	        	return;
	        }
	        */
	        //人员信息处理
	        sql = "select id from hrmresource where outkey='" + outkey + "' and outkey is not null ";
	        rs.execute(sql);
	        if (rs.next())
	        {
	          int hrmid = rs.getInt("id");
	          sql = "update hrmresource set lastname='"+lastname+"',sex='"+sex+"',certificatenum='"+certificatenum+"',mobile='"+mobile+"',email='"+email+"'," +
	          		"jobtitle='"+jobtitle+"',managerid='"+managerid+"',departmentid='"+departmentid+"',subcompanyid1='"+subcompanyid+"',telephone='"+telephone+"'," +
	          		"mobilecall='"+mobilecall+"',dsporder='"+dsporder+"',status='"+loginstatus+"' where id="+hrmid;
	          
	          rs.execute(sql);
	          writeLog("[HrmOrgManager.synHrmResource] 更新人员sql:" + sql);
	          
	        }else{
	        	
	          rs.executeProc("HrmResourceMaxId_Get", "");
	          rs.next();
	          int maxid = rs.getInt(1);

	          if (maxid > 0)
	          {
	          	String password = "0659C7992E268962384EB17FAFE88364";
	          	String loginid = "2"+ workcode + mobile.substring(mobile.length() - 4 );

	            sql ="insert into hrmresource(id,loginid,password,workcode,lastname,departmentid,subcompanyid1,systemlanguage,sex,mobile,certificatenum,status,managerid,dsporder,jobtitle,telephone,mobilecall,outkey,email) " +
	            	 "values ("+maxid+",'"+loginid+"','"+password+"','"+workcode+"','"+lastname+"','"+departmentid+"','"+subcompanyid+"',7,'"+sex+"','"+mobile+"','" +
	            	 certificatenum+"','"+loginstatus+"','" + managerid + "','"+dsporder+"','" + jobtitle + "','"+telephone+"','"+mobilecall+"','"+outkey+"','"+email+"')";
	            rs.execute(sql);
	            
	            writeLog("[HrmOrgManager.synHrmResource] 新增人员sql:" + sql);
	            
	            sql="update HrmResource set createrid =1, createdate ='"+today+"', lastmodid = 1, lastmoddate = '"+today+"' where id = "+maxid;
	            rs.execute(sql);
	            
	            String para = maxid + separator + managerid + separator + departmentid + separator + subcompanyid + separator + "10" + separator+""+separator;
	            rs.executeProc("HrmResource_Trigger_Insert", para);
	            
	            String sql_1 = "insert into HrmInfoStatus (itemid,hrmid,status) values(1," + maxid + ",1)";
	            rs.execute(sql_1);
	            String sql_2 = "insert into HrmInfoStatus (itemid,hrmid) values (2," + maxid + ")";
	            rs.execute(sql_2);
	            String sql_3 = "insert into HrmInfoStatus (itemid,hrmid) values (3," + maxid + ")";
	            rs.execute(sql_3);
	            String sql_10 = "insert into HrmInfoStatus (itemid,hrmid) values(10," + maxid + ")";
	            rs.execute(sql_10);
	          }
	        }
	        writeLog("同步完成");
	    }
    	
	  }
	
	/**
	 * 同步分部
	 * @param subObj
	 */
	public void SynSubCompany(){
		
		RecordSetDataSource dataSource = new RecordSetDataSource("EHR");
	    String sql="select * from compview";
	    dataSource.execute(sql);
	    while(dataSource.next()) {
	    	
	    	String outkey = dataSource.getString("orgid");
	    	String sub_code = dataSource.getString("orgnum");
			String sub_name = dataSource.getString("name");
			String parent_key = dataSource.getString("orgpid");
			String status = dataSource.getString("isdel");//1:正常，2:停⽤，-1:逻辑删除
			
			String subcomid="0"; //分部ID
			String supsubcomid="0"; //上级分部ID
			
			//查询上级分部ID
			RecordSet recordSet=new RecordSet();
			sql="select id from HrmSubCompany where outkey='"+parent_key+"' and outkey<>''";
			recordSet.execute(sql);
			if(recordSet.next()){
				supsubcomid=recordSet.getString("id");
			}
			
			writeLog("[HrmOrgManager.SynSubCompany] 同步分部：sub_code:"+sub_code+" sub_name:"+sub_name+" parent_key:"+parent_key+" status:"+status+" supsubcomid:"+supsubcomid);
			
			//根据编码查询当前分部是否存在
			sql="select id from HrmSubCompany where outkey='"+outkey+"' ";
			recordSet.execute(sql);
			
			if(recordSet.next()){ //如果存在就更新
				
				sql = "update HrmSubCompany set subcompanyname='" + sub_name + "',subcompanydesc='" + sub_name + "',supsubcomid='" + supsubcomid + "',canceled='0' where outkey='" + outkey + "'";
				writeLog("[HrmOrgManager.SynSubCompany] 更新分部 sql:"+sql);
				recordSet.execute(sql);
				
			}else{
				
				sql="insert into hrmsubcompany(subcompanyname,subcompanydesc,companyid,supsubcomid,subcompanycode,outkey) values ('" + sub_name + "','" + sub_name + "',1," + supsubcomid + ",'" + sub_code + "','"+outkey+"')";
				recordSet.execute(sql);
				writeLog("[HrmOrgManager.SynSubCompany]  新增分部 sql:"+sql);
				
				sql="select id from HrmSubCompany where outkey = '" +outkey + "'"; //查询新增的分部ID
				recordSet.execute(sql);
				if(recordSet.next()){
					subcomid=recordSet.getString("id"); //分部ID
					//设置权限
					recordSet.execute("insert into leftmenuconfig (userid,infoid,visible,viewindex,resourceid,resourcetype,locked,lockedbyid,usecustomname,customname,customname_e)  select  distinct  userid,infoid,visible,viewindex," + 
							subcomid + ",2,locked,lockedbyid,usecustomname,customname,customname_e from leftmenuconfig where resourcetype=1  and resourceid=1");
					recordSet.execute("insert into mainmenuconfig (userid,infoid,visible,viewindex,resourceid,resourcetype,locked,lockedbyid,usecustomname,customname,customname_e)  select  distinct  userid,infoid,visible,viewindex," + 
							subcomid + ",2,locked,lockedbyid,usecustomname,customname,customname_e from mainmenuconfig where resourcetype=1  and resourceid=1");
				}		
			}
			
			//delSubCompany(orgId, dept_name);
	        if (status.equals("1"))
	        {
	          sql="update HrmSubCompany set canceled='1' where outkey='" + outkey + "'";
	          recordSet.execute(sql);
	          writeLog("[HrmOrgManager.SynSubCompany]  封存分部 sql:"+sql);
	        }
	    }
	
	}
	
	public void delSubCompany(String orgId, String shortname){
	    try
	    {
	      RecordSet rs = new RecordSet();
	      String sql = "";
	      sql = "select count(id) from hrmdepartment where EXISTS (select 1 from hrmsubcompany b where hrmdepartment.subcompanyid1=b.id and b.fid='" + 
	      orgId + "') and (canceled='0' or canceled is null)";
	      rs.executeSql(sql);
	      int rows = 0;
	      while (rs.next()) {
	        rows += Util.getIntValue(rs.getString(1), 0);
	      }
	      if (rows > 0)
	      {
	        writeLog("封存分部失败，该分部下有正常的部门，分部名称：" + shortname);
	        sql = "update HrmSubCompany set canceled='0' where fid='" + orgId + "'";
	        rs.executeSql(sql);
	      }
	      else
	      {
	        sql = "update HrmSubCompany set canceled='1' where fid='" + orgId + "'";
	        rs.executeSql(sql);
	        writeLog("封存分部成功," + sql);
	      }
	    }
	    catch (Exception e)
	    {
	      writeLog("封存分部失败," + e);
	    }
	  }
	
	/**
	 * 同步部门
	 */
	public void SynDept(){
		
	    RecordSet rs = new RecordSet();
	    
	    RecordSetDataSource dataSource = new RecordSetDataSource("EHR");
	    String sql="select * from orgview";
	    dataSource.execute(sql);
	    while(dataSource.next()) {
	    	
			String outkey = dataSource.getString("orgid");
			String departmentname = dataSource.getString("name");
			String departmentcode = dataSource.getString("");
			String supdeptkey = dataSource.getString("orgpid");
			String subcomkey = dataSource.getString("orgpid");
			String canceled = dataSource.getString("isdel");
		      
		      int subcomid = 0;
		      int supdeptid = 0;
		      
		      //查询上级部门
		      sql="select id,subcompanyid1 from hrmdepartment where outkey = '" +supdeptkey + "'";
		      rs.execute(sql);
		      if (rs.next()){
		    	  supdeptid = Util.getIntValue(rs.getString("id"), 0);
		    	  subcomid = Util.getIntValue(rs.getString("subcompanyid1"), 0);
		      }else{
		    	  sql="select id from HrmSubCompany where outkey = '" +supdeptkey + "'";
		    	  rs.execute(sql);
		    	  if(rs.next()){
		    		  subcomid=rs.getInt("id");
		    	  }
		      }
		      
		      writeLog("[HrmOrgManager.SynSubCompany] 同步部门：departmentname:"+departmentname+" departmentcode:"+departmentcode+" supdeptkey:"+supdeptkey+" subcomkey:"+subcomkey+" supdeptid:"+supdeptid+" subcomid:"+subcomid);
		        
		      //查询当前部门是否存在
		      sql="select id from hrmdepartment where outkey = '" +outkey +"'";
		      rs.execute(sql);
	        
		      if(rs.next()){
	        	
	        	sql = "update hrmdepartment set subcompanyid1=" + subcomid + ", departmentname='" + departmentname +"',departmentmark='" + departmentname + "',supdepid=" + supdeptid + ",canceled='0' where outkey='" + outkey + "'";
		        rs.execute(sql);
		        
		        writeLog("[HrmOrgManager.SynSubCompany] 更新部门sql:" + sql);
	        	
		      }else{
	    	
	        	sql = "insert into hrmdepartment(departmentname,departmentmark,subcompanyid1,supdepid,showorder,departmentcode,canceled,outkey) values ('" + 
	        	departmentname + "','" +departmentname +"'," + subcomid +"," + supdeptid + ",'','" + departmentcode + "',0,'"+outkey+"')";
	        	
	            rs.execute(sql);
	            writeLog("[HrmOrgManager.SynSubCompany] 新增部门sql:" + sql);
		      }
	        
		      if(canceled.equals("1")){
		    	  sql="update hrmdepartment set canceled='1' where outkey='" + outkey + "'";
		    	  rs.execute(sql);
		          writeLog("[HrmOrgManager.SynDept]  封存部门 sql:"+sql);
		      }
	    }
	   
	  }
	
	/**
	 * 封存部门
	 * @param code
	 * @param shortname
	 */
	public void delDepartment(String departmentcode, String shortname)
	  {
	    try
	    {
	      RecordSet rs = new RecordSet();
	      String sql = "";
	      int id = 0;
	      rs.executeSql("select id from hrmdepartment where departmentcode='" +departmentcode + "'");
	      if (rs.next()) {
	        id = Util.getIntValue(rs.getString(1), 0);
	      }
	      sql ="select id from hrmresource where status in (0,1,2,3) and EXISTS (select 1 from hrmdepartment b where hrmresource.departmentid=b.id and b.id = " + id + ") union select id from hrmdepartment where (canceled = '0' or canceled is null) and id in (select id from hrmdepartment where supdepid =" + id + ")";
	      rs.executeSql(sql);
	      int rows = 0;
	      while (rs.next()) {
	        rows += Util.getIntValue(rs.getString(1), 0);
	      }
	      if (rows > 0)
	      {
	    	  writeLog("封存部门失败，该部门下有正常的人员，部门名称：" + shortname);
	      }
	      else
	      {
	        sql = "update hrmdepartment set canceled='1' where departmentcode='" + departmentcode + "'";
	        rs.executeSql(sql);
	        writeLog("封存部门成功!" + sql);
	      }
	    }
	    catch (Exception e)
	    {
	    	writeLog("封存部门失败," + e);
	    }
	  }

	/**
	 * 同步岗位
	 */
	public void SynJobtitle(){
	    try
	    {
		    RecordSet rs = new RecordSet();
		      
		    RecordSetDataSource dataSource = new RecordSetDataSource("EHR");
		    String sql="select * from postview";
		    dataSource.execute(sql);
		    while(dataSource.next()) {
		    	
				String outkey = dataSource.getString("postid");
				String jobtitlename = dataSource.getString("postname");
			    String jobtitlemark = dataSource.getString("postname");
			    String jobtitlecode = dataSource.getString("");
		      
		        //查询当前岗位是否存在
		        sql = "select id from hrmjobtitles where outkey='" + outkey + "'";
		        rs.executeSql(sql);
		        if(rs.next()){
		        	
		        	sql = "update hrmjobtitles set jobtitlename='"+jobtitlename+"',jobtitlemark='"+jobtitlemark +"' where outkey='" + outkey + "'";
			        rs.executeSql(sql);
			        
			        writeLog("[HrmOrgService.SynJobtitle]更新岗位 sql:" + sql);
		        }else{
		        	
		        	sql="insert into hrmjobtitles(jobtitlename,jobtitlemark,jobtitlecode,outkey) values ('"+jobtitlename+"','"+jobtitlemark+"','"+jobtitlecode+"','"+outkey+"')";
		        	rs.executeSql(sql);
		          
		        	writeLog("[HrmOrgService.SynJobtitle]新增岗位 sql:" + sql);
		        	
		        }
				
				
		    }
	    }catch (Exception e)
	    {
	      writeLog("同步岗位失败," + e);
	    }
	}

	
}

